<template>
  <div>
    <base-window size="larger" :unique="false" class-name="agenda-task" :show.sync="dialogFormVisible" :title="title" @closed="reset">
      <div class="schedule-content">
        <div class="schedule-scroll-content">
          <el-form ref="formRef" :model="form" label-position="top" size="mini">

            <!-- 工单新建表单 -->
            <task-edit-view :plan-time-config="planTimeConfig" class="agenda-task-edit-view" v-if="form.startTime" :plan-start-time="form.startTime" :plan-end-time="form.endTime" ref="agendaTaskRef"/> 
        
            <!-- 服务部门 负责人 协同人 -->
            <agenda-task-header @executor="getExecutor" @synergyUserList="getSynergyUserList" ref="agendaTaskHeaderRef"></agenda-task-header>   
          </el-form>
        </div>

        <div class="schedule-scroll-content">
          <div class="users-time">
            <div class="clash">
              <p class="clash-tip">
                <!-- <i v-if="clashCount" class="iconfont icon-jinggao"></i> 
                <i v-else class="iconfont icon-yitongguo"></i> 
                {{clashCount ? `${clashCount}人日程有冲突` : '暂无日程冲突'}} -->
              </p>
              <div class="clash-right">
                <!-- <el-select v-model="clashType" placeholder="冲突类型" clearable>
                  <el-option label="完全冲突" :value="1"></el-option>
                  <el-option label="完全不冲突" :value="2"></el-option>
                  <el-option label="部分冲突" :value="3"></el-option>
                </el-select> -->
                <el-select class="work-state"
                           v-model="statusList"
                           multiple
                           collapse-tags
                           :placeholder="$t('common.base.workState')">
                  <el-option
                    v-for="item in userStateList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    <div class="schedule-work-state-item">
                      <span class="state-color-icon" :style="{backgroundColor: item.color}"></span>
                      <span>{{item.label}}</span>
                    </div>
                  </el-option>
                </el-select>
                <el-button class="bnt-add-user" @click="selectApproveUser" type="primary" plain icon="el-icon-plus" size="mini">{{$t('calendar.detail.addPeople')}}</el-button>
              </div>  
            </div>

            <p v-if="GanttData.length > 0" class="users-time-tips">{{$t('calendar.detail.oprateText')}}</p>
          
            <div class="container">
              <gantt-chart
                :gantt-data="GanttData"
                :time-section="GanttTime"
                :chart-max-height="ChartHeight"
                type="task"/>
            </div> 
  
          </div> 
        </div>


      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('common.base.close')}}</el-button>
        <el-button type="primary" @click="submit">{{$t('common.base.save')}}</el-button>
      </div>

      <div class='task-allot-user-content agenda-user-card'>
        <base-panel width='470px' :show.sync="showUserCard">
          <user-card
            :state-color-map="stateColorMap"
            :task="{}"
            :show-synergy-button="true"
            :user-id="excutorUserId"
            @close="showUserCard=false" 
            @setExecutor="setExecutor"
            @setSynergy="setSynergy"
            @deleteSynergyUser="deleteSynergyUser"/>
        </base-panel>
      </div>

    </base-window >
    <!-- start 工单发起质保审批弹窗 -->
    <propose-approve-dialog ref="proposeApproveCalendar" :unique='false' @success="onApproveSuccessHandler" />
  <!-- end 工单发起质保审批弹窗 -->
  </div>
</template>

<script>
import ProposeApproveDialog from '@src/modules/task/editAllot/components/ProposeApproveDialog.vue'
import moment from 'moment'
import UserCard from '@src/modules/task/components/TaskAllotModal/UserCard/UserCard.tsx'
import TaskAllotExecutor from '@src/modules/task/components/TaskAllotModal/TaskAllotExcutor/TaskAllotExcutor.tsx'
import { getRootWindow } from '@src/util/dom'
import { getStateColorMap } from '@src/api/SettingApi'
import * as CalendarApi from '@src/api/CalendarApi.ts'
import _ from 'lodash';
import { safeNewDate } from '@src/util/time';
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { getTimestamp } from 'pub-bbx-utils';
export default {
  name: 'agendar-task-dailog',
  inject:['initData'],
  props: {
    taskStartTime: {
      type: String,
      default: ''
    },
    taskEndTime: {
      type: String,
      default: ''
    },
    agendaInfo: {
      type: Object,
      default: ()=>({})
    },
    planTimeConfig: {
      type: Number,
      default: 30
    }
  },
  data() {
    return {
      showUserCard: false,
      excutorUserId: '',
      stateColorMap: {},
      
      dialogFormVisible: false,
      title: this.$t('calendar.detail.createTaskAgenda'), 
      form: {
        name: '',
        type: 2,
        startTime: '',
        endTime: '',
        descr: '',
        isRepeat: 0,
        repeatType: '0',
        acceptNotice: 0,
        refuseNotice: 0,
        noticeType: 1,
        noticeContent: '',
        minutes: '0',
        users:[]
      },
      clashType: '',
      statusList:[],
      userStateList: [],
      clashCount: 0,

      executorId:'',
      synergies:[],

      GanttData: [],
      GanttCurrentTime: safeNewDate().getTime(),
      // 定时器
      marker: null,
      ChartWidth: 80,
      ChartHeight: 600,
      customerId: '',
    }
  },
  computed: {
    tabHeight(){
      return 'calc(100vh) - 196px';
    },
    loginUser(){
      return this.initData.loginUser 
    },
    selectUsers(){
      return this.form.users
    },
    GanttTime(){
      // 时间轴以计划开始时间和完成时间  
      return [moment(this.form.startTime).format('YYYY/MM/DD HH:mm'), moment(this.form.endTime).format('YYYY/MM/DD HH:mm')]
    },
  },
  watch: {
    taskStartTime: {
      immediate: true,
      handler() {
        // console.info('selectstartTime::', this.startTime);
        if(this.taskStartTime) {
          // 日程开始和结束时间
          this.form.startTime = this.taskStartTime
          this.form.endTime = this.taskEndTime
          this.getClashUserTime() 
        }
      }
    },
    agendaInfo: {
      immediate: true,
      deep: true,
      handler() {
        // console.info('this.agendaInfo::', this.agendaInfo);
        if(this.agendaInfo.id) {
          const type = this.agendaInfo.type;
          this.title = type == 3 ? this.$t('calendar.detail.editcommonAgenda') : (type == 1 ? this.$t('calendar.detail.editEventAgenda') : this.$t('calendar.detail.editTaskAgenda'))
          this.getAgendaInfo(this.agendaInfo.id)
        }
      }
    },
    selectUsers: {
      deep: true,
      handler() {
        this.getClashUserTime() 
      }
    },
    clashType:{
      handler() {
        this.getClashUserTime() 
      }
    },
    statusList:{
      handler() {
        this.getClashUserTime() 
      }
    },
  },
  created () {
    this.$eventBus.$on('agendar-task-select-customer', this.handleSelectCustomerId);
    this.$eventBus.$on('agenda-task-user-card', this.handleUserCard)
    this.$eventBus.$on('agenda-task-plan-start-time', this.handleStartTime)
    this.$eventBus.$on('agenda-task-plan-end-time', this.handleEndTime)
  },
  mounted () { 
    // this.marker = setInterval(() => {
    //   this.GanttCurrentTime += 1000
    // }, 1000) 
    // this.form.users.push(this.loginUser);
    // 初始化工作状态和颜色
    this.initWorkState()
  },
  destroyed () {
    this.$eventBus.$off('agendar-task-select-customer', this.handleSelectCustomerId);
    this.$eventBus.$off('agenda-task-user-card', this.handleUserCard)
    this.$eventBus.$off('agenda-task-plan-start-time', this.handleStartTime)
    this.$eventBus.$off('agenda-task-plan-end-time', this.handleEndTime)
  },
  methods: {
    reset(){
      this.title = this.$t('calendar.detail.createTaskAgenda')
      this.form.startTime = this.startTime
      this.form.endTime = this.endTime
      this.form.users = []
      this.GanttData = []
      this.clashCount = 0
      this.clashType = ''
      this.statusList = []
      this.$emit('reset')
    },
    handleStartTime(e){
      this.form.startTime = e
      this.getClashUserTime() 
    }, 
    handleEndTime(e){
      this.form.endTime = e
      this.getClashUserTime() 
    }, 
    handleSelectCustomerId(id){
      if(!id) return
      this.customerId = id
      this.getClashUserTime()
    },
    handleUserCard(event){
      this.excutorUserId = event.userId
      this.showUserCard = true
    },
    // user-card 设置负责人
    setExecutor(user){
      this.executorId = user ? user.userId : ''
      if(this.initData.allotByTag){
        this.$refs.agendaTaskHeaderRef.handlerTeamUsersChange(user ? [user] : []) 
      } else {
        this.$refs.agendaTaskHeaderRef.executorChangedHandler(user)
      }  
    },
    getExecutor(user){
      let originExecutorId = this.executorId 
      this.executorId = user?.userId
      if(user && user.userId) {
        const list = this.form.users.filter(item=>item.userId != user.userId)
        this.form.users = [...list, user]
      } else {
        if(originExecutorId) {
          const index = this.form.users.findIndex(item=>item.userId == originExecutorId)
          if(index > -1) {
            this.form.users.splice(index, 1)
          }
        }
      }
    },
    setSynergy(user) {
      this.$refs.agendaTaskHeaderRef.synergyUserListChangedHandler(user)
    },
    deleteSynergyUser(user){
      this.$refs.agendaTaskHeaderRef.synergyUserCloseHandler(user)
    },
    getSynergyUserList(users){
      this.synergies = users
      let old = this.form.users
      this.form.users = [...old, ...users]
    },
    getClashUserTime(){
      if(this.form.startTime && this.form.endTime && this.customerId && this.form.users.length) {
        this.getAgendaUsersTime()
        // this.getAgendaUsersTimeNum()
      } else {
        this.GanttData = []
      }
    },
    initWorkState(){
      getStateColorMap().then(res => {      
        this.stateColorMap = res || {}
        let list = []
        let userStateMap = {}
        try {
          let rootWindow = getRootWindow(window)
          let initData = JSON.parse(rootWindow?._init || '{}')
          userStateMap = initData.userStateMap
        } catch (error) {
          userStateMap = {}
          console.error('error', error)
        }
        for (let userStateKey in userStateMap) {
          let userState = {
            key: userStateKey,
            value: userStateKey,
            label: userStateKey,
            color: res[userStateKey]
          }
          list.push(userState)
        }
        this.userStateList = list
      })
    },
    async getAgendaUsersTime(){
      try {
        const params = {};
        params.customerId = this.customerId
        params.planStartTime = safeNewDate(this.form.startTime).getTime() 
        params.planEndTime = safeNewDate(this.form.endTime).getTime() 
        params.userIds = this.form.users.map(item=>item.userId)
        params.clashType = this.clashType ? this.clashType : 0
        params.userStateList = this.statusList
        const res = await CalendarApi.getTaskAgendaUsersTime(params);
        if(res.code != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.GanttData = res.result?.list || []
      } catch (err) {
        console.error('err', err);
      }
    },
    async getAgendaUsersTimeNum(){
      if(!this.form.users.length) return
      try {
        const params = {};
        params.customerId = this.customerId
        params.planStartTime = safeNewDate(this.form.startTime).getTime()
        params.planEndTime = safeNewDate(this.form.endTime).getTime()
        params.userIds = this.form.users.map(item=>item.userId)
        params.clashType = this.clashType
        params.statusList = this.statusList
        const res = await CalendarApi.getTaskAgendaUsersTimeNum(params);
        if(res.code != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.clashCount = res.result || 0
      } catch (err) {
        console.error('err', err);
      }
    },
    show() {
      this.dialogFormVisible = true
    },
    handleClose(user) {
      this.form.users.splice(this.form.users.indexOf(user), 1);
    },
    selectApproveUser(){
      // 判断是否选择了客户
      if(!this.customerId) return this.$platform.alert(this.$t('calendar.tips.customerTip'));
      let selected = _.cloneDeep(this.form.users)
      let obj = {};
      selected = selected.reduce((cur, next) => {
        obj[next.userId] ? '' : obj[next.userId] = true && cur.push(next);
        return cur;
      }, [])
      let options = {
        title: this.$t('calendar.detail.addPeople'), // [选填] 默认值为 '请选择人员'
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        unique: false,
        haveRole: true,
        mode: BaseSelectUserModeEnum.Filter
      }

      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0 || !res.data) return
          let list = res.data.users || []
          // list = list.filter(item=>item.userId != this.loginUser.userId) 
          // this.form.users = [...this.form.users, ...list] ;
          this.form.users = list

          if(!res.data.length){
            this.GanttData = [];
          }
          // this.$refs.agendaTaskHeaderRef.synergyUserListChangedHandler(list)
        })
        .catch((err) => {
          console.warn(err)
        })
    },
    async getPostParams(){
      try {
        return await this.$refs.agendaTaskRef?.getPostParams() || {}
      } catch (error) {
        console.error('error', error);
      }
    },
    async submit() {
      this.form.startTime = getTimestamp(this.form.startTime)
      this.form.endTime = getTimestamp(this.form.endTime)
      if(safeNewDate(this.form.startTime).getTime() > safeNewDate(this.form.endTime).getTime()) {
        return this.$platform.notification({
          title: this.$t('calendar.limit.timeLimit'),
          type: 'error'
        });
      }
      if(safeNewDate(this.form.startTime).getTime() < safeNewDate().getTime()) {
        return this.$platform.notification({
          title: this.$t('common.modal.PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE'),
          type: 'error'
        });
      }
      try {
        let flag = this.$refs.agendaTaskRef?.qualityValidate() 
        if(flag) return
        if(this.$refs.agendaTaskRef.qualityField?.setting?.allowProduct == 2 && this.$refs.agendaTaskRef.form?.quality?.qualityStatus == 'OUT') {
          let data = this.$refs.agendaTaskRef.qualityField.setting
          this.showApprove(data)
          return
        }
        this.submitSuccess()
      } catch (error) {
        console.error(error);
      }
    },
    async submitSuccess() {
      const params = await this.getPostParams()
      params.task.planStartTime = this.form.startTime
      params.task.planEndTime = this.form.endTime
      const form = {}
      form.taskForm = params
      form.allotForm = {
        executorId: this.executorId,
        synergies: this.synergies
      }
      if(!this.executorId) return this.$platform.alert(this.$t('common.modal.TASK_NO_EXECUTOR_MESSAGE'));
      this.dialogFormVisible = false;
      this.$emit('submitCreateTask', form);
    },
    // 展示审批弹窗
    showApprove(data) {
      this.$refs.proposeApproveCalendar.openDialog(data)
    },
    onApproveSuccessHandler(value) {
      this.approveForm = value
      this.submitSuccess()
    },
    // 获取日程详情
    async getAgendaInfo(agendaId){
      try {
        let res = await CalendarApi.getAgendaCalendarInfo({agendaId});
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.form = res.data.agendaInfo;
        this.form.startTime = this.agendaInfo.startTime
        this.form.endTime = this.agendaInfo.endTime
        this.form.minutes = String(this.form.minutes)
        this.form.repeatType = String(this.form.repeatType)
        this.form.users = res.data.users
      } catch (err) {
        console.error('err', err);
      }
    },
  },
  components: {
    [ProposeApproveDialog.name]: ProposeApproveDialog,
    UserCard,
    'agenda-task-header': {
      name: 'agenda-task-header',
      inject: ['initData'],
      data() {
        return {
          taskAllotExecutorComponent: new TaskAllotExecutor()
        }
      },
      computed: {
        isAllotByTag() {
          return this.initData.allotByTag 
        }
      },
      methods: {
        handlerTeamChange(selectTeams) {
          this.taskAllotExecutorComponent.selectTeams = selectTeams
        },
        handlerTeamUsersChange(selectTeamUsers) {
          if(this.showUserCard) this.showUserCard = false;
          this.$emit('executor', selectTeamUsers[0])
          this.taskAllotExecutorComponent.selectTeamUsers = selectTeamUsers
        },
        executorChangedHandler(executorUser) {
          if(this.showUserCard) this.showUserCard = false;
          this.$emit('executor', executorUser ? executorUser : {})
          this.taskAllotExecutorComponent.selectDeptUsers = executorUser ? [executorUser] : []
        },
        synergyUserListChangedHandler(user) {
          // 这里通过选人组件获取的user是数组，通过user-card获取的是对象 
          let origin = _.clone(this.taskAllotExecutorComponent.synergyUserList)
          if(Array.isArray(user)) {
            this.updateSynergyUserList(user)
          } else {
            const { displayName, head, staffId, userId } = user
            const _user = { displayName, head, staffId, userId }
            const index = origin.findIndex(item=>item.userId == _user.userId)
            if(index == -1) {
              origin.push(_user)
              this.updateSynergyUserList(origin)
            }
          }
        },
        updateSynergyUserList(users){
          this.$emit('synergyUserList', users)
          this.taskAllotExecutorComponent.synergyUserList = users
        },
        synergyUserCloseHandler(user){
          const synergyUserList = _.clone(this.taskAllotExecutorComponent.synergyUserList)
          const index = synergyUserList.findIndex(item=>item.userId == user.userId)
          synergyUserList.splice(index, 1)
          this.$emit('synergyUserList', synergyUserList)
          this.taskAllotExecutorComponent.synergyUserList = synergyUserList
        },
        debouncedRemoveDepartmentUser(user){
          if(this.showUserCard) this.showUserCard = false;
          this.$emit('executor', [])
          this.taskAllotExecutorComponent.selectDeptUsers = []
        },
        chooseDepartmentUsers(user){
          if(this.showUserCard) this.showUserCard = false;
          this.$emit('executor', [])
          this.taskAllotExecutorComponent.selectDeptUsers = []
        },
        initialize() {
          // 
        }
      },
      mounted() {
        this.taskAllotExecutorComponent.handlerTeamChange = this.handlerTeamChange
        this.taskAllotExecutorComponent.handlerTeamUsersChange = this.handlerTeamUsersChange
        this.taskAllotExecutorComponent.executorChangedHandler = this.executorChangedHandler
        this.taskAllotExecutorComponent.synergyUserListChangedHandler = this.synergyUserListChangedHandler
        this.taskAllotExecutorComponent.synergyUserCloseHandler = this.synergyUserCloseHandler
        this.taskAllotExecutorComponent.debouncedRemoveDepartmentUser = this.debouncedRemoveDepartmentUser
        this.taskAllotExecutorComponent.initialize = this.initialize
        this.taskAllotExecutorComponent.synergyUserList = []
        this.taskAllotExecutorComponent.selectTeams = []
        this.taskAllotExecutorComponent.selectTeamUsers = []
      },
      render(h) {
        return (
          <div>
            { this.isAllotByTag && this.taskAllotExecutorComponent.renderTaskAllotExecutorHeaderRow(this.$t('common.base.serviceDepartment'), this.taskAllotExecutorComponent.renderTeamSelect()) }
            { this.isAllotByTag && this.taskAllotExecutorComponent.renderTaskAllotExecutorHeaderRow(this.$t('common.label.principalName'), this.taskAllotExecutorComponent.renderTeamUserSelect()) }
            { !this.isAllotByTag && this.taskAllotExecutorComponent.renderTaskAllotExecutorHeaderRow(this.$t('common.label.principalName'), this.taskAllotExecutorComponent.renderDepartmentUserSelect(false)) }
            { this.taskAllotExecutorComponent.renderTaskAllotExecutorHeaderRow(this.$t('common.fields.synergies.displayName'), this.taskAllotExecutorComponent.renderSynergySelect()) }
          </div>
        )
      }
    }
  }
  
}
</script>
<style lang="scss" scoped>
.schedule-content{
  display: flex;
  height: 100%; 
  .schedule-scroll-content{
    height: 100%;
    overflow-y: auto;
    >.el-form{
      width: 100%;
      height: 100%;
    }
    >.users-time{
      width: 100%;
    }

    &:nth-child(1){
      flex: 1;
    }
    &:nth-child(2){
      flex: 1;
    }
  }
  .el-form {
    width: 50%;
    padding-right: 12px;
    border-right: 1px solid #eee;
    .no-left {
      ::v-deep .el-form-item__content{
        margin-left: 0!important;
      }
    }
    .user-tag {
      background-color: #fff;
      background-image: none;
      border-radius: 2px;
      border: 1px solid #e0e1e2;
      padding-left: 10px;
      .el-tag--mini{
        margin-right: 10px;
      }
    }
    .noti-time{
      margin-right: 15px;
    } 

    
  }
  
  .users-time{
    width: 50%; 
    display: flex;
    flex-direction: column;
    padding-left: 12px;
    .clash{
      display: flex;
      // justify-content: right;
      height: 40px;
      line-height: 40px;
      padding: 0;
      .clash-tip{
        min-width: 100px;
        .icon-yitongguo {
          color: #52C41A;
        }
        .icon-jinggao {
          color: #FF4D4F;
        }
      }
      .clash-right {
        flex: 1;
        display: flex;
        justify-content: flex-end;
      }
      .el-select{
        max-width: 150px;
        margin: 0 5px;
      }
      .work-state{
        max-width: 150px;
        ::v-deep .el-tag {
          display: flex;
          align-items: center;
          max-width: 65px;
          @include text-ellipsis();
          .el-select__tags-text {
            display: inline-block;
            max-width: 40px;
            @include text-ellipsis();
          }
          .el-tag__close.el-icon-close {
            right: -3px;
          }
        }
      }
      .bnt-add-user{
        padding: 0 15px;
        height: 32px;
        line-height: 32px;
        margin-top: 4px;
        border-radius: 4px;
        margin-left: 5px;
      }
    }
    .users-time-tips {
      padding: 0 10px;
      margin: 0;
      color: $color-warning;
    }
    .el-table {
      flex: 1;
      height: calc(100vh - 196px);
      ::v-deep .el-table_1_column_1  {
        border-bottom: none!important;
      }
      ::v-deep td.is-hidden > *{
        visibility: visible!important;
      }
    }
  }

  .schedule-work-state-item{
    display: flex;
    align-items: center;
    .state-color-icon{
      display: inline-block;
      border-radius: 50%;
      width: 10px;
      height: 10px;
      margin-right: 10px;
    }
  }

  .agenda-user-card{
    .base-panel{
      height: 450px;
      margin: auto;
      .user-card{
        padding: 30px 10px 0px 10px;
      }
    }
  }

}
</style>

<style lang="scss">
.agenda-task {
  .layx-html {
    overflow-x: hidden!important;
    .base-window-content-body {
      overflow: hidden;
    }
  }
}
.schedule-content{
  .task-allot-executor-header-row{
    margin-bottom: 10px;
    margin-right: 0;
    .task-allot-executor-header-row-label{
      color: #333;
      display: block;
      min-width: auto;
    }
    .task-allot-table-user{
      width: 100%;
    }
    .placeholder-text{
      font-size: 12px;  
    }
  }
  .agenda-task-form{
    width: auto;
    margin: 0;
    padding-left: 0;
    color: #333;
    border-top: 1px solid #eee;
    .form-item label{
      padding-left: 0;
    }
  }

  .agenda-task-edit-view{
    height: auto!important;
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    
  }

  .ui-input-block {
    border-radius: 4px;
  }

  .task-form-container {
    .task-form-container-left {
      width: 100%;
    }
  }
}
</style>